package com.StarStudio.Utils;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


//@RestController
//@RequestMapping("/test")
public class CellTicket {

    private static int tickets = 100;

    @Resource
    RedissonClient redissonClient;

    @GetMapping
    public void test(){
        for (int i = 0; i < 2000; i++) {
            new Thread(()->{
                RLock lock = redissonClient.getLock("lock");
                boolean isLock = false;
                try {
                    isLock = lock.tryLock(1,10, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                if (isLock){
                    try {
                        sell();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }finally {
                        lock.unlock();
                    }
                }
            }).start();
        }
    }

//    public static void main(String[] args) {
//        for (int i = 0; i < 2000; i++) {
//            new Thread(()->{
//                sell();
//            }).start();
//        }
//    }

    public static void sell(){
        if (tickets > 0){
            tickets --;
            System.out.println("剩余票数："+tickets);
        }
    }

}
